/**
 * @author Chris Ray
 * Created on 11:17:21 PM Nov 7, 2011
 *
 */
package view;

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Iterator;
import java.util.Observable;
import java.util.Observer;

import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import battleFieldModel.BattleField;

import worldModel.Direction;
import worldModel.InvalidMoveException;
import worldModel.Item;
import worldModel.LargeHeal;
import worldModel.MediumHeal;
import worldModel.Navigator;
import worldModel.SmallHeal;
import worldModel.World;
import worldModel.WorldTile;

/**
 * @author Chris Ray Created on 11:17:21 PM Nov 7, 2011
 */
public class WorldView extends MasterViewPanel implements Observer {

	/**
	 * @author Chris Ray Created on 1:30:05 AM Nov 10, 2011
	 * 
	 */
	private static final long serialVersionUID = 4177722480763550363L;
	private Navigator currentNav;
	private World currentWorld;
	private Image navigatorImage;
	private Image worldFloorImage;

	/**
	 * @param m
	 * @param cont
	 *            if true, triggers loading of navigator.dat file, if false a
	 *            new navigator is created.
	 * @author Chris Ray Created on 11:18:19 PM Nov 7, 2011
	 * 
	 */
	public WorldView(MasterView m, Integer cont) {

		super(m);

		currentNav = null;
		// load navigator.dat
		if (cont == 1)
			loadNavigator();
		else
			createNavigator();
		currentWorld = new World(currentNav);
		// plugging in the new navigator image
		navigatorImage = new ImageIcon("images/stickwalk2.gif").getImage();
		worldFloorImage = new ImageIcon("images/floorPanel.png").getImage();
		currentWorld.addObserver(this);
		this.setFocusable(true);
		this.addKeyListener(new WorldKeyListener());

	}

	/**
	 * @author Chris Ray Created on 4:01:09 PM Nov 9, 2011
	 * 
	 */
	private void createNavigator() {
		currentNav = new Navigator();

	}

	/**
	 * 
	 * @author Chris Ray Created on 5:06:34 PM Nov 9, 2011
	 * @throws FileNotFoundException
	 * 
	 */
	private void loadNavigator() {
		try {
			currentNav = Library.loadNavigator();
		} catch (Exception e) {
			if (currentNav == null) {
				JOptionPane
						.showMessageDialog(this,
								"Could not load navigator.dat; starting New Game instead.");
				currentNav = new Navigator();
			}
		}
	}

	@Override
	public void paint(Graphics g) {
		super.paint(g);
		Iterator<WorldTile> tiles = currentWorld
				.tiles(currentNav.getLocation());

		int navRow = currentNav.getLocation().row;
		int navLwRow = currentNav.getLeeway().row;
		int navCol = currentNav.getLocation().col;
		int navLwCol = currentNav.getLeeway().col;
		int r, c, x, y;
		while (tiles.hasNext()) {
			WorldTile currentTile = tiles.next();
			r = navRow - currentTile.getLocation().row;
			c = navCol - currentTile.getLocation().col;

			// coordinates for worldTile images to be drawn
			x = (((280 + (32 * r)) - (32 * c)) + navLwRow) - navLwCol;
			y = 170 - (32 * c) - (32 * r) - navLwRow - navLwCol;

			g.drawImage(worldFloorImage, x, y, null);
		}
		g.drawImage(navigatorImage, 304, 160, null);
	}

	/**
	 * 
	 * @author Chris Ray Created on 5:06:29 PM Nov 9, 2011
	 * @param n
	 * 
	 */
	public void saveNavigator() {
		Library.saveNavigator(currentNav);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.util.Observer#update(java.util.Observable, java.lang.Object)
	 * 
	 * @author Chris Ray Created on 1:57:51 AM Nov 10, 2011
	 */
	@Override
	public void update(Observable arg0, Object arg1) {
		if (arg1 == null)
			this.repaint();
		else if (arg1 instanceof BattleField)
			m.changeView(Views.BATTLE, arg1);
		else if ((arg1 instanceof Views) && (arg1 == Views.PREVIOUS))
			m.changeView(Views.PREVIOUS, null);

	}

	private class WorldKeyListener implements KeyListener {

		/*
		 * (non-Javadoc)
		 * 
		 * @see java.awt.event.KeyListener#keyPressed(java.awt.event.KeyEvent)
		 * 
		 * @author Chris Ray Created on 2:57:54 AM Nov 10, 2011
		 */

		@Override
		public void keyPressed(KeyEvent k) {
			try {

				switch (k.getKeyCode()) {
				case KeyEvent.VK_DOWN: {
					currentWorld.move(Direction.SOUTH_EAST);
					repaint();
					System.out.println("down. Navigator's location: "
							+ currentNav.getLocation().row + " "
							+ currentNav.getLocation().col);
					break;
				}

				case KeyEvent.VK_UP: {
					currentWorld.move(Direction.NORTH_WEST);
					repaint();
					System.out.println("up. Navigator's location: "
							+ currentNav.getLocation().row + " "
							+ currentNav.getLocation().col);
					break;
				}

				case KeyEvent.VK_LEFT: {
					currentWorld.move(Direction.SOUTH_WEST);
					repaint();
					System.out.println("left. Navigator's location: "
							+ currentNav.getLocation().row + " "
							+ currentNav.getLocation().col);
					break;
				}

				case KeyEvent.VK_RIGHT: {
					currentWorld.move(Direction.NORTH_EAST);
					repaint();
					System.out.println("right. Navigator's location: "
							+ currentNav.getLocation().row + " "
							+ currentNav.getLocation().col);
					break;
				}

				case KeyEvent.VK_X: { // pause

					int numSmall = 0, numMed = 0, numLarge = 0;
					for (Item i : currentNav.getInventory()) {
						if (i instanceof SmallHeal)
							numSmall++;
						if (i instanceof MediumHeal)
							numMed++;
						if (i instanceof LargeHeal)
							numLarge++;
					}
					String sText = "", mText = "", lText = "";
					int optionsToAdd = 0;
					if (numSmall > 0) {
						sText = "Use Small Heal (" + numSmall + ")";
						optionsToAdd++;
					}
					if (numMed > 0) {
						mText = "Use Medium Heal (" + numMed + ")";
						optionsToAdd++;
					}
					if (numLarge > 0) {
						lText = "Use Large Heal (" + numLarge + ")";
						optionsToAdd++;
					}
					String[] options = new String[2 + optionsToAdd];
					while (optionsToAdd > 0) {
						if (numSmall > 0) {
							options[1 + optionsToAdd] = sText;
							optionsToAdd--;
						}
						if (numMed > 0) {
							options[1 + optionsToAdd] = mText;
							optionsToAdd--;
						}
						if (numLarge > 0) {
							options[1 + optionsToAdd] = lText;
							optionsToAdd--;
						}
						optionsToAdd--;
					}
					options[0] = "Cancel";
					options[1] = "Quit";

					int choice = JOptionPane.showOptionDialog(null,
							"Paused: What would you like to do?",
							"Player Health: "
									+ currentNav.getPlayer().getHealth(),
							JOptionPane.DEFAULT_OPTION,
							JOptionPane.QUESTION_MESSAGE, null, options,
							options[0]);
					if (currentNav.getPlayer().getHealth() < 100) {
						for (Item i : currentNav.getInventory())
							if ((i instanceof SmallHeal)
									&& (options[choice] == sText)) {
								i.activateEffect(currentNav);
								currentNav.getInventory().remove(i);
							} else if ((i instanceof MediumHeal)
									&& (options[choice] == mText)) {
								i.activateEffect(currentNav);
								currentNav.getInventory().remove(i);
							} else if ((i instanceof LargeHeal)
									&& (options[choice] == lText)) {
								i.activateEffect(currentNav);
								currentNav.getInventory().remove(i);
							}
					} else if ((choice != 0) && (choice != 1))
						JOptionPane
								.showMessageDialog(
										null,
										"You are already at 100% Health! Item not used! What did you think would happen? Noob!");
					if (choice == 1) {
						// Quit (change view back to main menu)
						m.changeView(Views.TITLE, null);
						Library.saveNavigator(currentNav);
					}
					// Show us what we chose.
					System.out.println(choice);
					System.out.println(options[choice]);
					break;
				}

				}
			} catch (Exception ex) {

			}

		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see java.awt.event.KeyListener#keyReleased(java.awt.event.KeyEvent)
		 * 
		 * @author Chris Ray Created on 2:57:54 AM Nov 10, 2011
		 */
		@Override
		public void keyReleased(KeyEvent k) {
			// TODO Auto-generated method stub

		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see java.awt.event.KeyListener#keyTyped(java.awt.event.KeyEvent)
		 * 
		 * @author Chris Ray Created on 2:57:54 AM Nov 10, 2011
		 */
		@Override
		public void keyTyped(KeyEvent k) {
			// TODO Auto-generated method stub

		}

	}

	@Override
	public String toString() {
		return "WORLD";
	}

}
